package com.example.takeaway.api;

import cn.hutool.core.util.IdUtil;
import com.example.takeaway.common.R;
import com.example.takeaway.config.MinioTemplate;
import com.example.takeaway.config.OssConfig;
import com.example.takeaway.constant.OssSceneEnum;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author 邢晨旭
 * {@code @date} 2023/10/19
 */
@RestController
public class UploadApi {

    @Resource
    MinioTemplate minioTemplate;

    @Resource
    OssConfig ossConfig;

    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file, @RequestParam("scene") Integer sceneCode) throws IOException {
        OssSceneEnum scene = OssSceneEnum.getByScene(sceneCode);
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String uuid = IdUtil.fastSimpleUUID();
        String newFileName = scene.getPath() + uuid + suffix;
        minioTemplate.putObject(file.getBytes(), newFileName, file.getContentType());
        return R.ok(ossConfig.getEndpoint() + ossConfig.getBucket() + newFileName);
    }

}
